//
//  TJStatusViewModel.m
//  TJSinaWeiBo_OC
//
//  Created by 唐后能 on 16/4/28.
//  Copyright © 2016年 itheima. All rights reserved.
//

#import "TJStatusViewModel.h"
#import "TJAccountViewModle.h"
#import "TJNetWorkTool.h"

@implementation TJStatusViewModel
// 获取全局共享单例.
+(instancetype)shareStatusViewModel{

    static TJStatusViewModel *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

// 加载微博信息.
- (void)loadStatusWithsince_id:(int)since_id andMax_id:(int)max_id andCallBack:(void (^)(NSError *error,NSArray *statuses)) callBack {

    // 1,请求的URLString.
    NSString *URLString = @"https://api.weibo.com/2/statuses/home_timeline.json";
    
    // 2,请求参数.
    NSMutableDictionary *parameters = @{@"access_token":[[TJAccountViewModle shareAccountViewModle] account].access_token};
    // 拼接上拉刷新和下拉刷新需要的参数.
    if (since_id>0) {
        parameters[@"since_id"] = [NSNumber numberWithInt:since_id];
    }
    if (max_id>0) {
        parameters[@"max_id"] = [NSNumber numberWithInt:max_id - 1];
    }
    
    // 3,发送请求.
    [[TJNetWorkTool shareNetWorkTool] GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary* responseObject) {
        // 请求成功.
//        TJLog(@"%@",responseObject);
        
        NSArray *statuses = responseObject[@"statuses"];
        
        // 定义一个可变的数组,用来装微博模型.
        NSMutableArray *statusModels = [NSMutableArray arrayWithCapacity:statuses.count];
        
        for (NSDictionary *dict in statuses) {
            TJStatus *status = [TJStatus statusWithDict:dict];
            [statusModels addObject:status];
        }
        // 成功回调.
        callBack(nil,statusModels);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 请求失败
        TJLog(@"%@",error);
        // 失败回调.
        callBack(error,nil);
    }];
    
    
}

@end
